from PySide6 import QtSql
import getpath
class DBdata:
    def getConnection(self):
        accessFile=getpath.getpath()+"/../data.sqlite"
        self.connection = QtSql.QSqlDatabase.database();#connID, false);

        if (self.connection.isValid()):
            if (self.connection.isOpen()):
                return True
        else:
            self.connection = QtSql.QSqlDatabase.addDatabase("QSQLITE");#', connID);
        self.connection.setDatabaseName(accessFile);

        if (not self.connection.open()):
            qDebug()<<"open failed";
            return false;
        return True;
    def nextSampleId(self):
        n=0;
        model = QtSql.QSqlTableModel()
        model.setTable("program")
        model.select()
        record = model.record(0)
        n=record.value("sampleid")#.toInt() #取
        # print(type(n),dir(n))
        record.setValue("sampleid",n+1)
        model.setRecord(0, record)
        model.submitAll();
        return  n + 1
# long CDBdata::nextId()
# {
#     long n=0;
#     QSqlTableModel* model = new QSqlTableModel(NULL);
#     model->setTable("program");
#     model->select();
#     QSqlRecord record = model->record(0);
#     n=record.value("seqence_id").toInt();#取
#     #增加1
#     record.setValue("seqence_id",QVariant((int)n+1));
#     model->setRecord(0, record);
#     model->submitAll();
#     return  n + 1;
# }

# void CDBdata::removeVoltNew(long id)
# {
#     QSqlQuery query;
#     QString cmd;
#     cmd.setNum(id);
#     cmd="delete from voltnew where id="+cmd;
#     qDebug()<<cmd;
#     query.exec(cmd);

# }
    def insertTmpid(self,id):
        query=QtSql.QSqlQuery()
        cmd="insert into tmpid(sampleid) values(%d)" % (id)
        print(cmd)
        query.exec(cmd);

# void CDBdata::getChannels(QHash<QString, ChannelAD> * pgchannels)
# {
#     qDebug("getChannels====");
#     QSqlQuery q("SELECT * FROM channel");

#     #pgchannels->clear();
#     while (q.next())
#     {
#         qDebug("got rows");
#         ChannelAD a;
#         QSqlRecord rec = q.record();
#         a.channel=rec.value("channel").toInt();
#         a.color=rec.value("color").toInt();
#         a.ele=rec.value("ele").toString();
#         a.enable=rec.value("enable").toBool();
#         a.title=rec.value("title").toString();
#         #pgchannels->append(a);
#         (*pgchannels)[a.ele]=a;
#     }
#     qDebug()<<pgchannels;
# }
    def clearAll(self):
        query=QtSql.QSqlQuery()
        query.exec("delete  from tmpid");
if __name__ == "__main__":
    db=DBdata()
    print("dbdata")
    if db.getConnection():
        print(db.nextSampleId())
    pass
